import router from './router'
import { getToken } from '@/utils/auth'
import NProgress from 'nprogress'
import store from './store'
import notification from 'ant-design-vue/es/notification'
import { checkLogin, getArgumentsToken, logout, getQueryVariable } from './utils/authCenter'
NProgress.configure({ showSpinner: false })

// 路由白名单，不需要登陆
const allowRouteList = ['home', 'login']

const loginRoutePath = '/login'
const defaultRoutePath = '/home'

router.beforeEach((to, from, next) => {
  NProgress.start()
  function checkToken() {
    if (to.path === loginRoutePath) {
      next({ path: defaultRoutePath })
      NProgress.done()
    } else {
      // user info is null

      if (Object.values(store.getters.userInfo).length === 0) {
        store
          .dispatch('user/getInfo')
          .then(() => {
            const redirect = decodeURIComponent(from.query.redirect || to.path)
            if (to.path === redirect) {
              // set the replace: true so the navigation will not leave a history record
              next({ ...to, replace: true })
            } else {
              // 跳转到目的路由
              next({ path: redirect })
            }
          })
          .catch(() => {
            notification.error({
              message: '错误',
              description: '请求用户信息失败，请重试!',
            })
            // 失败时，获取用户信息失败时，调用登出，来清空历史保留信息
            store.dispatch('user/logout').then(() => {
              logout()
            })
          })
      } else {
        next()
      }
    }
  }

  var loginStatus = getArgumentsToken()
  if (getToken()) {
    checkToken()
  } else {
    // 免登录名单
    next()
    // if (allowRouteList.includes(to.name)) {
    //   var isToken = getQueryVariable('isToken')
    //   if (!loginStatus && isToken != 0) {
    //     checkLogin()
    //   } else {
    //     next()
    //   }
    // } else {
    //   if (loginStatus) {
    //     checkToken()
    //   } else {
    //     checkLogin()
    //   }

    //   NProgress.done()
    // }
  }
})

router.afterEach(() => {
  NProgress.done()
})
